package logger

import (
	"ginlogger/config"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var lg *zap.Logger

// InitLogger 初始化Logger
func InitLogger(cfg *config.LogConfig) (err error) {
	writeSyncer := getLogWriter(cfg.Filename, cfg.MaxSize, cfg.MaxBackups, cfg.MaxAge)
	encoder := getEncoder()
	var l = new(zapcore.Level)
	err = l.UnmarshalText([]byte(cfg.Level))
	if err != nil {
		return
	}

	var cores []zapcore.Core
	cores = append(cores, zapcore.NewCore(encoder, writeSyncer, l))
	if gin.Mode() == gin.DebugMode {
		cores = append(cores, zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), l))
	}
	core := zapcore.NewTee(cores...)

	lg = zap.New(core, zap.AddCaller())
	zap.ReplaceGlobals(lg) // 替换zap包中全局的logger实例，后续在其他包中只需使用zap.L()调用即可
	return
}

func getEncoder() (encoder zapcore.Encoder) {
	// if !encoderType {
	// 	encoderType = ""
	// }
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
	encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder

	// if encoderType == "console" {
	// 	encoder = zapcore.NewConsoleEncoder(encoderConfig)
	// } else {
	// 	encoder = zapcore.NewJSONEncoder(encoderConfig)
	// }
	encoder = zapcore.NewJSONEncoder(encoderConfig)
	return
}

func getLogWriter(filename string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    maxSize,
		MaxBackups: maxBackup,
		MaxAge:     maxAge,
	}
	return zapcore.AddSync(lumberJackLogger)
}
